import React from "react";
import {
  BrowserRouter,
  NavLink,
  Route,
  Prompt,
  withRouter
} from "react-router-dom";
import Home from "./component/home";
import News from "./component/news";
import About from "./component/about";
import Login from "./component/login";
import store from "./store";
// 拦截器
const Lanjie = withRouter(props => {
  // 拦截器执行与否通过登录信息来确定
  const { user } = store.getState().loginReducer;
  console.log(user);
  return (
    <Prompt
      when={!user}
      message={(loaction, action) => {
        if (loaction.pathname === "/news") {
          alert("您还没有登陆");
          props.history.replace("/login");
          return false; // 这里false 是用来组织进入新闻页
        }
        return true; // 允许跳转
      }}
    />
  );
});
// 主组件

const Index = () => {
  return (
    <BrowserRouter>
      <nav>
        <NavLink to="/home">首页</NavLink>&nbsp;&nbsp;&nbsp;
        <NavLink to="/news">新闻页</NavLink>&nbsp;&nbsp;&nbsp;
        <NavLink to="/about">关于</NavLink>&nbsp;&nbsp;&nbsp;
        <NavLink to="/login">登录</NavLink>
      </nav>
      {/* 拦截 */}
      <Lanjie />
      <main>
        <Route path="/home" component={Home} />
        <Route path="/news" component={News} />
        <Route path="/about" component={About} />
        <Route path="/login" component={Login} />
      </main>
    </BrowserRouter>
  );
};

export default Index;
